package io.hepu.robotize.util;

import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
import java.util.function.Predicate;

public class JCollection {

    private JCollection() {}

    /**
     * Removes from this list all of its elements that are contained in the
     * specified collection.
     *
     * @param list Target list to eliminate.
     * @param ec   Specified elements collection.
     */
    public static <T> List<T> eliminate(List<T> list, Collection<T> ec) {
        list.removeAll(ec);
        return list;
    }

    public static <T> Optional<T> find(Collection<T> list, Predicate<T> predicate) {
        return list.stream().filter(predicate).findAny();
    }

    /**
     * Convert a object to specified type list.
     *
     * @param obj  Target object to convert.
     * @param clzz Specified cast type class.
     * @param <T>  clzz
     * @return List<T>
     */
    public static <T> List<T> asList(Object obj, Class<T> clzz) {
        List<T> list = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                list.add(clzz.cast(o));
            }
        }
        return list;
    }

    /**
     * 判断集合是否相同
     *
     * @param <T> 数组类型
     * @return 是否相同
     */
    public static <T> boolean equals(List<T> one, List<T> two) {
        return CollectionUtils.isEqualCollection(one, two);
    }

    /**
     * 是否集合
     *
     * @param obj 判断对象
     * @return 是否集合
     */
    public static boolean isCollection(Object obj) {
        return obj.getClass().isArray() || obj instanceof Collection;
    }

    /**
     * 对象转为集合
     * @param obj 转换对象
     * @return 对象列表
     */
    public static List<Object> asList(Object obj) {
        return isCollection(obj) ? asList(obj, Object.class) : Collections.singletonList(obj);
    }
}
